import { Definition } from '../common/definition';
import { CsFundDouble } from '../common/csFundDouble';
import { CsDouble } from '../common/csDouble';
import { MeasurementUnit } from '../basicData/measurementUnit';
import { CommodityCategory } from '../basicData/commodityCategory';
import { SubCommodity } from './subCommodity';
import { Util } from '../../utils/util';
import { Engine } from '../engine';
import { TestConfig } from '../common/testConfig';

export class Commodity {
    constructor({
        id = '', code = '', name = '', qrCode = '',
        coverUri = '', remark = '', enabled = true,
        purchasePrice = undefined,
        retailPrice = undefined,
        wholesalePrice = undefined,
        unit = undefined,
        cost = undefined,
        category = undefined,
        count = undefined,
        subCommodityList = undefined,
        multiStandard = false,
        initInventory = undefined,
        coverImgCachePath = '',
        metalAccountTypeId = null, // 关联贵金属账户类型ID
        metalCode = null,          // 商品贵金属code
        isMetalSelf = false,       // 贵金属自身，如果是所有操作会直接影响 metalAccountTypeId 指定的账户，和库存。
        sorder = 0
    } = {}) {
        this.id = id;
        this.code = code;
        this.name = name;
        this.qrCode = qrCode;
        this._coverUri = coverUri;
        this.remark = remark;
        this.enabled = enabled;

        this.purchasePrice = purchasePrice !== undefined ? purchasePrice : CsFundDouble.zero();
        this.retailPrice = retailPrice !== undefined ? retailPrice : CsFundDouble.zero();
        this.wholesalePrice = wholesalePrice !== undefined ? wholesalePrice : CsFundDouble.zero();
        this.unit = unit !== undefined ? unit : MeasurementUnit.empty();
        this.cost = cost !== undefined ? cost : CsFundDouble.zero();
        this.category = category !== undefined ? category : CommodityCategory.empty();
        this.count = count !== undefined ? count : CsDouble.zero();

        this.subCommodityList = subCommodityList !== undefined ? subCommodityList : [];
        this.coverImgCachePath = coverImgCachePath;
        this.multiStandard = multiStandard;
        this.initInventory = initInventory !== undefined ? initInventory : [];

        this.metalAccountTypeId = metalAccountTypeId; // 关联贵金属账户类型ID
        this.metalCode = metalCode;          // 商品贵金属code
        this.isMetalSelf = isMetalSelf;
        this.sorder = sorder;
    }

    get coverUri() {
        if (TestConfig.commodityImgUrlDirectUrlTest) {
            //测试数据是完整的外部图片链接，不需要再拼接
            return this._coverUri || "";
        }
        else {
            return this._coverUri ? Definition.baseUrlWithoutService + this._coverUri : '';
        }
    }

    set coverUri(value) {
        this._coverUri = value;
    }

    get coverRelationPath() {
        return this._coverUri;
    }

    static clone(commodity) {
        const result = new Commodity({
            id: commodity.id,
            code: commodity.code,
            name: commodity.name,
            qrCode: commodity.qrCode,
            coverUri: commodity._coverUri,
            remark: commodity.remark,
            enabled: commodity.enabled,
            metalAccountTypeId: commodity.metalAccountTypeId,
            metalCode: commodity.metalCode,
            isMetalSelf: commodity.isMetalSelf,
            sorder: commodity.sorder
        });

        result.unit = MeasurementUnit.clone(commodity.unit);
        result.category = CommodityCategory.clone(commodity.category);
        result.cost = new CsDouble(commodity.cost.value);
        result.purchasePrice = new CsFundDouble(commodity.purchasePrice.value);
        result.retailPrice = new CsFundDouble(commodity.retailPrice.value);
        result.wholesalePrice = new CsFundDouble(commodity.wholesalePrice.value);
        result.multiStandard = commodity.multiStandard;
        result.count = new CsDouble(commodity.count.value);
        result.subCommodityList = commodity.subCommodityList.map(c => SubCommodity.clone(c));
        return result;
    }

    static fromJson(json) {
        const c = new Commodity({
            id: Util.jsonToString(json.id),
            code: Util.jsonToString(json.commodityCode),
            name: Util.jsonToString(json.commodityName),
            qrCode: Util.jsonToString(json.commodityBarcode),
            coverUri: Util.jsonToString(json.commodityImgs),
            remark: Util.jsonToString(json.remark),
            enabled: Util.jsonToBool(json.useState, false),
            metalAccountTypeId: Util.jsonToString(json.metalAccountTypeId),
            isMetalSelf: Util.jsonToBool(json.isMetalSelf, false),
            metalCode: Util.jsonToString(json.metalCode),
            sorder: Util.jsonToInt(json.sorder, 0),
        });

        c.unit = new MeasurementUnit(
            Util.jsonToString(json.commodityUnitId),
            Util.jsonToString(json.commodityUnit),
            Util.jsonToBool(json.unitDecimalSupport, true)
        );

        c.category = new CommodityCategory(
            Util.jsonToString(json.commodityCategoryId),
            Util.jsonToString(json.commodityCategoryName)
        );

        c.purchasePrice = Util.jsonToCsFundDouble(json.lineCostPrice, 0);
        c.retailPrice = Util.jsonToCsFundDouble(json.lineRetailPrice, 0);
        c.wholesalePrice = Util.jsonToCsFundDouble(json.lineTradePrice, 0);
        c.multiStandard = Util.jsonToBool(json.multiSpecs, false);
        c.subCommodityList = Array.isArray(json.specs)
            ? json.specs.map(item => SubCommodity.fromJson(item))
            : [];

        c.count = Util.jsonToCsDouble(json.count, 0);

        for (const item of c.subCommodityList) {
            item.unit = c.unit;
        }

        return c;
    }

    toJson() {
        const ret = {};

        if (this.id) ret.id = this.id;
        ret.commodityCode = this.code;
        ret.commodityName = this.name;
        ret.commodityBarcode = this.qrCode;
        ret.commodityImgs = this._coverUri;
        ret.commodityUnit = this.unit.name;
        ret.commodityUnitId = this.unit.id;
        ret.useState = this.enabled ? 1 : 2;
        ret.commodityCategoryId = this.category.id;
        ret.remark = this.remark;
        ret.lineCostPrice = this.purchasePrice.value;
        ret.lineRetailPrice = this.retailPrice.value;
        ret.lineTradePrice = this.wholesalePrice.value;
        ret.createOrg = Engine.profile?.org?.orgId;
        ret.multiSpecs = this.multiStandard ? 1 : 0;
        ret.specName = this.subCommodityList.length > 0 ? this.subCommodityList[0].standard : '';
        ret.specs = this.subCommodityList.map(item => item.toJson());
        ret.metalAccountTypeId = this.metalAccountTypeId;
        ret.metalCode = this.metalCode;
        ret.isMetalSelf = this.isMetalSelf ? 1 : 0;
        ret.sorder = this.sorder;

        return ret;
    }

    // 对象传递拷贝 与  fromJson 一一对应
    toCopyJson() {

        const ret = {};

        ret.id = this.id;
        ret.commodityCode = this.code;
        ret.commodityName = this.name;
        ret.commodityBarcode = this.qrCode;
        ret.commodityImgs = this._coverUri;
        ret.remark = this.remark;
        ret.useState = this.enabled ? 1 : 2;

        ret.commodityUnit = this.unit.name;
        ret.commodityUnitId = this.unit.id;
        ret.unitDecimalSupport = this.unit.supportDecimal;

        ret.commodityCategoryId = this.category.id;
        ret.commodityCategoryName = this.category.name;

        ret.lineCostPrice = this.purchasePrice.value;
        ret.lineRetailPrice = this.retailPrice.value;
        ret.lineTradePrice = this.wholesalePrice.value;
        ret.multiSpecs = this.multiStandard ? 1 : 0;

        ret.specs = this.subCommodityList.map(item => item.toCopyJson());
        ret.count = this.count.value;

        ret.metalAccountTypeId = this.metalAccountTypeId;
        ret.metalCode = this.metalCode;
        ret.isMetalSelf = this.isMetalSelf;
        return ret;

    }

    clearImg() {
        this.coverImgCachePath = '';
        this._coverUri = '';
    }

    standardInfo() {
        if (this.subCommodityList.length === 1) {
            return this.subCommodityList[0].standard;
        }
        return `多规格 X ${this.subCommodityList.length}`;
    }
}
